<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
	
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Iterator" %>
<%@ page import ="com.easyattendance.services.AddClassService" %>
<%@ page import ="com.easyattendance.model.Class" %>
<%@ page import ="com.easyattendance.services.AddTeacherService" %>
<%@ page import ="com.easyattendance.model.Teacher" %>
<%@ page import="com.easyattendance.services.AddSubjectService"%>
<%@ page import="com.easyattendance.services.AddAllTimeSlotsService"%>
<%@ page import ="com.easyattendance.model.Subject" %>
<%@page import="com.easyattendance.model.AllTimeSlots"%>
<%@page import="com.easyattendance.services.LoginService"%>
<%@page import="com.easyattendance.services.TimeTableService"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Section - Set Time Table</title>
<!-- <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> -->
<jsp:include page="../includeFiles.jsp" />

</head>

<body class="left-sidebar" onload="getValues()">

<!-- Session check : user logged in or not/ press back button -->
<jsp:include page="../common/checkSession.jsp" />
<jsp:include page="../common/checkTeacherRole.jsp" />

<% 
	String currentUser = (String) session.getAttribute("currentUser");
	AddTeacherService teacherService = new AddTeacherService();
	String deptId = teacherService.getSectionIdByTeacherId(currentUser);	
	AddClassService classService = new AddClassService();
	String semYearId = classService.getClassIdByTeacherId(currentUser);
	TimeTableService timeTableService = new TimeTableService();
	
	LoginService loginserv = new LoginService();
	String user_role = loginserv.getUserType(currentUser);
%>

	<!-- Wrapper -->
	<div id="wrapper">

		<!-- Content -->
		<div id="content">
			<div id="content-inner">
				
				<!-- Login -->
						<div id="login_content">
						<header>
							<h2>Set Time Table</h2>
						</header>
						<% String deleteCookie = (String)request.getAttribute("addSuccess");
							if(deleteCookie != null){ %>
							<script type="text/javascript">clearCookie();</script>
						<% } %>
						<span class="success_msg">${addSuccess}</span>
						<span class="error_msg">${addFail}</span>
						<div class="submit_errors_msg">
							<ul>
								<li id="submit_is_field_empty" class="submit_errors">All * fields are required.</li>
							</ul>
						</div>
						
						<form action="${pageContext.request.contextPath}/ReadExcelTTServlet">
							<input type="submit" value="Import TimeTable From Excel" class="button add_button" tabindex="1">
							<!-- <input type="hidden" id="action_type" name="action_type" value="import"> -->
						</form>
						
						<form name="setTimeTableForm" action="${pageContext.request.contextPath}/AddTimeTableServlet" method="post"  onsubmit="return checkFormErrors();">
							<!-- Hidden fields for tbl_timetable -->
							
							<div>
							<!-- <input type="hidden" id="action_type" name="action_type" value="input"> -->
								<input id="timetable_id" type="hidden">
								<!-- Foreign Keys :  Remove if not required. -->
								
								<input id="dept_id" type="hidden">
							</div>
							<!-- Day of Week -->
							<div>
								<label>Select Day of Week: <span class="error_msg">*</span></label>
								<select name="days_select" id="days_select" tabindex="1" value=<script>getCookie("days_select")</script> >
									<option value="">Select day of week
									<option name="Monday" value="Monday">Monday
									<option name="Tuesday" value="Tuesday">Tuesday
									<option name="Wednesday" value="Wednesday">Wednesday
									<option name="Thursday" value="Thursday" >Thursday
									<option name="Friday" value="Friday">Friday
									<option name= "Saturday" value="Saturday">Saturday
								</select>
							</div>
							<span class="error_msg">${dayDropdown}</span>
							<% String day = request.getParameter("day");%>
							
							<% if(day!= "") {%>
							
							<!-- Time Slot of Day-->
							<div>
							<% AddAllTimeSlotsService service = new AddAllTimeSlotsService();
							
							//List timeSlots = service.listAllTimeSlotsByDepartment(deptId);
							List timeSlots = service.listAllUnoccupiedTimeSlots(deptId, day, semYearId);
							%>
								<label>Select Time Slot: <span class="error_msg">*</span></label>
								<select name="timeslot_select" id="timeslot_select" tabindex="2" value=<script>getCookie("timeslot_select")</script>>
									<option value="Choose Time Slot" value="">Choose Time Slot
									<% Iterator iterator = timeSlots.iterator(); 
										for(int i=0; i < timeSlots.size()-1; i++){  
											String temp = (String) iterator.next();
									%>
										<option value="<%=temp%>"><%=temp%>
									<% } %>
									
								</select>
							</div>
							<% } %>
							<span class="error_msg">${timeslotDropdown}</span>
							<!-- Teacher -->
							<%
								day = request.getParameter("day");
								String timeslot = request.getParameter("timeSlot");
							%>
							
							<% if(day!= "" && timeslot!= "") {%>							
							<div>
							
								<input id ="daySelected" name="daySelected" type="hidden" value=<%=day %>>
								<input id ="timeSlotSelected" name="timeSlotSelected" type="hidden" value=<%=timeslot %>>
							
								<% teacherService = new AddTeacherService();
									List<Teacher> teachers = teacherService.listTeachersOnDayForTimeSlot(day, timeslot, currentUser);
									Iterator<Teacher> teacherItr = teachers.iterator();
									System.out.println("teacher size: "+teachers.size());
									Teacher tempTeacher=null;
								%>
							
								<label>Select Teacher: <span class="error_msg">*</span></label>
								<select name="teacher_select" id="teacher_select" tabindex="3"><!--  value=<script>getCookie("teacher_select")</script> -->
								<option value="">Select Teacher
									<% while(teacherItr.hasNext()) { %>
											<%  tempTeacher = (Teacher) teacherItr.next();
												String teacherName = tempTeacher.getTeacher_name();
												String teacherId = tempTeacher.getTeacher_id(); %>
									<option value=<%=teacherId%>><%=teacherName%>&nbsp;<%=tempTeacher.getTeacher_lname() %>
									<% } %>
								</select>
							</div>	
							<% } %>		
							<span class="error_msg">${subjectDropdown}</span>
								
							<% String teacher = request.getParameter("teacher"); %>
							
							
							<!--  Check teacher load for the selected day  -->
							<% if(teacher!= null) {
								int noOfLectures = timeTableService.getTotalTeacherLecturesPerDay(day, teacher);
								if(noOfLectures >= 4) {%>
									This teacher already has four lectures on <%=day%>. You cannot add more lectures for this teacher.
								<%} else { %>
							
									<!-- Subject -->
									
									<% if (teacher != null) {
										AddSubjectService subjectService = new AddSubjectService();
										classService = new AddClassService();
										//String semYearId = semYearService.getClassIdByTeacherId(currentUser);
										List subjects = subjectService.listSubjectsByTeacherId(teacher, semYearId);
										Iterator subjectItr = subjects.iterator();
										System.out.println("subject size: " + subjects.size()); %>
										
										<div>
										
											<% if(subjects.isEmpty()) { %>
												<label> This teacher has no subjects left for this timeslot in this class </label>
											<%} else {%>
											<label>Choose Subject: <span class="error_msg">*</span></label> 
											<select name="subject_select" id="subject_select" tabindex="4" value=<script>getCookie("subject_select")</script>>
												<option value="">Choose Subject
												<% while (subjectItr.hasNext()) {
														Subject tempSubject = (Subject) subjectItr.next();
														String subjectName = tempSubject.getSubject_name();
														String subjectId = tempSubject.getSubject_id();	%>
												<option value=<%=subjectId%>><%=subjectName%>
												<%}%>
											</select>
											<%}%>
											</div>
									<%}%>
							
								<span class="error_msg">${teacherDropdown}</span>
							
	
								<input id ="teacherSelected" name="teacherSelected" type="hidden" value=<%=teacher%>>
								<input id ="section_id" name="section_id" type="hidden" value=<%=teacherService.getSectionEmailIdByTeacherId(currentUser)%> >
								<input id ="subjectSelected" name="subjectSelected" type="hidden" value="<%=request.getParameter("subject") %>" >
								
								<div>	
									<input type="submit" value="Add to Time-table" class="button" tabindex="5" >
								</div>
							<%}%>
						<%}%>
						</form>
					</div>
				
			</div>
		</div>

		<!-- Sidebar -->
		<div id="sidebar">

			<!-- Sidebar Header - Logo & Name -->
			<jsp:include page="../common/sidebarHeader.jsp" />

			<jsp:include page="teacherMenu.jsp" />

			<!-- Sidebar Footer Content -->
			<jsp:include page="../common/sidebarFooter.jsp" />

		</div>

	</div>	
	<script type="text/javascript">
		$(function(){
			$("#setTimeTable").addClass("current_page_item");
		});
		var contextPath='<%=request.getContextPath()%>';
	</script>
	
	
	<!--  For drop down values -->
	<script type="text/javascript">
	$(".submit_errors_msg").hide();
	$(".submit_errors").hide();
	
	function checkFormErrors(){
		if(isAnyFieldEmpty($('#days_select'),$('#teacher_select'),$('#timeslot_select'),$('#subject_select'))){
			return true;
		}
		return false;
	}
	
		$(function () {
		    var temp = 0;
		    $('#days_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				setCookie("days_select",day);
				window.location.replace(contextPath + "/views/teacher/setTimeTable.jsp?day=" + day);
		    });      
		});
		
		// To get timeslot and day selected and populate subjects in subj drop down
		$(function () {
		    var temp = 0;
		    $('#timeslot_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				var timeslot = $("#timeslot_select").val();
				setCookie("timeslot_select",timeslot);
				window.location.replace(contextPath + "/views/teacher/setTimeTable.jsp?" + "day=" + day + "&timeSlot=" + timeslot);
		    });      
		});
		
		//To get subject selected from drop down
		$(function () {
		    var temp = 0;
		    $('#teacher_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				var timeslot = $("#timeslot_select").val();
				var teacher = $("#teacher_select").val();
				var teacher_text = $("#teacher_select :selected").text();
				setCookie("teacher_select",teacher);
				setCookie("teacher_select_text",teacher_text);
				window.location.replace(contextPath + "/views/teacher/setTimeTable.jsp?day=" +day+"&timeSlot="+timeslot+ "&teacher=" + teacher);
		    });      
		});
		
		$(function () {
		    var temp = 0;
		    $('#subject_select').click(function () {        
		    	temp++;
		        if (temp == 2) {
		            $(this).change();
		            temp = 0;
		        }         
		    }).change (function () {
		    	var day = $("#days_select").val();
				var timeslot = $("#timeslot_select").val();
				var teacher = $("#teacher_select").val();
				var teacher_text = $("#teacher_select :selected").text();
				var subject = $("#subject_select").val();
				$('#subjectSelected').attr("value",subject);
				setCookie("subject_select",subject);
				window.location.replace(contextPath + "/views/teacher/setTimeTable.jsp?day=" +day+"&timeSlot="+timeslot+ "&teacher=" + teacher+ "&subject=" + subject);
		    });      
		});
		
		
		function getValues(){
			$("#days_select").val(getCookie("days_select"));
			$("#timeslot_select").val(getCookie("timeslot_select"));
			$("#teacher_select").val(getCookie("teacher_select"));
			$("#teacher_select :checked").text(getCookie("teacher_select_text"));
			$("#subject_select").val(getCookie("subject_select"));
		}
		
		function getCookie(name) { 
			var re = new RegExp(name + "=([^;]+)"); 
			var value = re.exec(document.cookie);
			return (value != null) ? unescape(value[1]) : null; 
		}
		
		function setCookie(name, value) {
			  var today = new Date(); 
			  var expiry = new Date(today.getTime() + 1 * 24 * 3600 * 1000); // plus 30 days
			  document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
		 }
		
		function clearCookie(){
			deleteCookie("days_select");
			deleteCookie("timeslot_select");
			deleteCookie("teacher_select");
			deleteCookie("subject_select");
			console.log("called");
			alert("Cookies Deleted");
		}
		
		function deleteCookie(name)
		{
			var expired = new Date(today.getTime() - 24 * 3600 * 1000); // less 24 hours
			document.cookie=name + "=null; path=/; expires=" + expired.toGMTString();
		}		
	</script>
</body>
</html>